package com.xf.service.impl;

import cc.mrbird.febs.common.datasource.starter.tenant.TenantBroker;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cc.mrbird.febs.common.datasource.starter.tenant.Tenant;
import com.xf.common.core.entity.QueryRequest;
import com.xf.common.core.entity.YesOrNoEnum;
import com.xf.common.core.entity.system.Role;
import com.xf.common.core.entity.system.RoleMenu;
import com.xf.common.core.exception.FebsException;
import com.xf.common.core.utils.FebsUtil;
import com.xf.mapper.TenantMapper;
import com.xf.service.IRoleMenuService;
import com.xf.service.IRoleService;
import com.xf.service.TenantService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 租户管理
 *
 * @author xufeng
 * @version 1.0
 * @date 2021/10/20
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements TenantService {

    @Resource
    private IRoleService iRoleService;
    @Resource
    private IRoleMenuService iRoleMenuService;

    /**
     * 创建工作空间
     *
     * @param tenant
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Tenant tenant) {
        //验证开始
        if (!"admin".equals(FebsUtil.getCurrentUsername())) {
            throw new FebsException("非admin用户无法创建工作空间");
        }
        //1.创建租户 租户1 admin为超级管理员
        //创建工作空间
        this.save(tenant);
        //2.创建默认的角色
        List<Role> roleList = iRoleService.list(new LambdaQueryWrapper<Role>().eq(Role::getIsDefault, YesOrNoEnum.Yes.getValue()));
        List<RoleMenu> roleMenuList = new ArrayList<>();
        Map<String, List<RoleMenu>> map = new HashMap<>();
        roleList.forEach(role -> {
            List<RoleMenu> roleMenus = iRoleMenuService.getRoleMenusByRoleId(String.valueOf(role.getRoleId()));
            map.put(role.getRoleId().toString(), roleMenus);
        });
        // 3.创建普通管理员的的菜单 t_role_menu
        TenantBroker.runAs(tenant.getTenantId(), (tenantId -> {
            roleList.forEach(role -> {
                List<RoleMenu> roleMenus = map.get(role.getRoleId().toString());
                role.setTenantId(null);
                role.setRoleId(null);
                //新增角色
                iRoleService.save(role);
                roleMenus.forEach(roleMenu -> {
                    roleMenu.setRoleId(role.getRoleId());
                    roleMenu.setTenantId(null);
                });
                iRoleMenuService.saveBatch(roleMenus);

            });

        }));

    }

    @Override
    public IPage<Tenant> getPage(QueryRequest request, Tenant tenant) {
        LambdaQueryWrapper<Tenant> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(tenant.getTenantName())) {
            queryWrapper.eq(Tenant::getTenantName, tenant.getTenantName());
        }
        Page<Tenant> page = new Page<>(request.getPageNum(), request.getPageSize());
        return this.page(page, queryWrapper);
    }
}
